<template>
  <div class="app-container">
    <!-- 搜索表单区域 -->
    <el-form 
      :model="queryParams" 
      ref="queryForm" 
      size="small" 
      :inline="true" 
      v-show="showSearch" 
      label-width="80px"
    >
      <el-form-item label="菜谱ID">
        <el-input
          v-model="queryParams.recipeId"
          placeholder="请输入菜谱ID"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      
      <el-form-item label="用户ID">
        <el-input
          v-model="queryParams.userId"
          placeholder="请输入收藏用户ID"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      
      <!-- 新增：用户名称查询条件 -->
      <el-form-item label="用户名称">
        <el-input
          v-model="queryParams.userName"
          placeholder="请输入用户名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">
          搜索
        </el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">
          重置
        </el-button>
      </el-form-item>
    </el-form>

    <!-- 操作按钮栏 -->
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['collect:favorites:add']"
        >新增</el-button>
      </el-col>
      
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['collect:favorites:edit']"
        >修改</el-button>
      </el-col>
      
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['collect:favorites:remove']"
        >删除</el-button>
      </el-col>
      
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['collect:favorites:export']"
        >导出</el-button>
      </el-col>
      
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <!-- 数据表格 -->
    <el-table 
      v-loading="loading" 
      :data="favoritesList" 
      @selection-change="handleSelectionChange"
      border
      stripe
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="收藏记录ID" align="center" prop="id" />
      <el-table-column label="菜谱ID" align="center" prop="recipeId" />
      <el-table-column label="收藏用户ID" align="center" prop="userId" />
      <!-- 新增：用户名称 -->
      <el-table-column label="用户名称" align="center" prop="userName" />
      <!-- 新增：用户头像 -->
      <el-table-column label="用户头像" align="center">
        <template #default="scope">
          <el-avatar :src="scope.row.userAvatar" size="small" v-if="scope.row.userAvatar">
            <img :src="scope.row.userAvatar" alt="用户头像">
          </el-avatar>
          <el-avatar size="small" v-else>
            <i class="el-icon-user"></i>
          </el-avatar>
        </template>
      </el-table-column>
      <el-table-column label="状态" align="center" prop="del">
        <template #default="scope">
          <el-tag :type="scope.row.del === 0 ? 'success' : 'danger'">
            {{ scope.row.del === 0 ? '正常' : '已删除' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['collect:favorites:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['collect:favorites:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页组件 -->
    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 弹窗表单 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="菜谱ID" prop="recipeId">
          <el-input v-model="form.recipeId" placeholder="请输入菜谱ID" />
        </el-form-item>
        
        <el-form-item label="收藏用户ID" prop="userId">
          <el-input v-model="form.userId" placeholder="请输入收藏用户ID" />
        </el-form-item>
        
        <!-- 新增：用户选择下拉框 -->
        <el-form-item label="选择用户" prop="userName">
          <el-select
            v-model="form.userName"
            placeholder="请选择用户"
            filterable
            remote
            :remote-method="remoteUserSearch"
            :loading="userLoading"
          >
            <el-option
              v-for="user in userOptions"
              :key="user.id"
              :label="user.userName"
              :value="user.userName"
              @click="handleUserSelect(user)"
            ></el-option>
          </el-select>
        </el-form-item>
        
        <el-form-item label="状态" prop="del">
          <el-radio-group v-model="form.del">
            <el-radio label="0">正常</el-radio>
            <el-radio label="1">已删除</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确认</el-button>
          <el-button @click="cancel">取消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { listFavorites, getFavorites, delFavorites, addFavorites, updateFavorites } from "@/api/collect/favorites"
import { selectUsers } from "@/api/collect/favorites"  // 导入用户查询接口
import Pagination from "@/components/Pagination"
import RightToolbar from "@/components/RightToolbar"

export default {
  name: "Favorites",
  components: { Pagination, RightToolbar },
  data() {
    return {
      loading: true,
      userLoading: false,  // 用户搜索加载状态
      ids: [],
      single: true,
      multiple: true,
      showSearch: true,
      total: 0,
      favoritesList: [],
      userOptions: [],  // 用户选择下拉框选项
      title: "",
      open: false,
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        recipeId: null,
        userId: null,
        userName: null  // 新增：用户名称查询参数
      },
      form: {
        id: null,
        recipeId: null,
        userId: null,
        userName: null,  // 新增：用户名
        userAvatar: null,  // 新增：用户头像
        createTime: null,
        del: 0 // 默认正常状态
      },
      rules: {
        recipeId: [
          { required: true, message: "菜谱ID不能为空", trigger: "blur" }
        ],
        userId: [
          { required: true, message: "收藏用户ID不能为空", trigger: "blur" }
        ],
        userName: [
          { required: true, message: "用户名称不能为空", trigger: "blur" }
        ],
        del: [
          { required: true, message: "状态不能为空", trigger: "change" }
        ]
      }
    }
  },
  created() {
    this.getList()
  },
  methods: {
    // 获取列表数据
    getList() {
      this.loading = true
      listFavorites(this.queryParams).then(response => {
        this.favoritesList = response.rows
        this.total = response.total
        this.loading = false
      }).catch(error => {
        console.error("获取列表失败:", error)
        this.loading = false
      })
    },
    
    // 远程搜索用户
    remoteUserSearch(query) {
      if (query !== '') {
        this.userLoading = true
        selectUsers({ userName: query }).then(response => {
          this.userOptions = response.data
          this.userLoading = false
        }).catch(error => {
          console.error("搜索用户失败:", error)
          this.userLoading = false
        })
      } else {
        this.userOptions = []
      }
    },
    
    // 选择用户时填充用户信息
    handleUserSelect(user) {
      this.form.userId = user.id
      this.form.userName = user.userName
      this.form.userAvatar = user.avatar
    },
    
    // 取消操作
    cancel() {
      this.open = false
      this.resetForm()
    },
    
    // 重置表单
    resetForm() {
      this.form = {
        id: null,
        recipeId: null,
        userId: null,
        userName: null,  // 重置用户名
        userAvatar: null,  // 重置用户头像
        createTime: null,
        del: 0
      }
      this.$refs.form && this.$refs.form.resetFields()
    },
    
    // 搜索操作
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    
    // 重置查询
    resetQuery() {
      this.$refs.queryForm && this.$refs.queryForm.resetFields()
      this.handleQuery()
    },
    
    // 多选事件
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    
    // 新增操作
    handleAdd() {
      this.resetForm()
      this.open = true
      this.title = "添加菜谱收藏"
    },
    
    // 修改操作
    handleUpdate(row) {
      this.resetForm()
      const id = row ? row.id : this.ids[0]
      getFavorites(id).then(response => {
        this.form = response.data
        this.open = true
        this.title = "修改菜谱收藏"
      }).catch(error => {
        console.error("获取详情失败:", error)
      })
    },
    
    // 提交表单
    submitForm() {
      this.$refs.form.validate(valid => {
        if (valid) {
          const request = this.form.id ? updateFavorites : addFavorites
          request(this.form).then(response => {
            this.$modal.msgSuccess(this.form.id ? "修改成功" : "新增成功")
            this.open = false
            this.getList()
          }).catch(error => {
            this.$modal.msgError("操作失败: " + (error.message || "未知错误"))
          })
        }
      })
    },
    
    // 删除操作
    handleDelete(row) {
      const ids = row ? [row.id] : this.ids
      this.$modal.confirm(`确认删除选中的${ids.length}条记录？`).then(() => {
        delFavorites(ids).then(() => {
          this.getList()
          this.$modal.msgSuccess("删除成功")
        }).catch(error => {
          this.$modal.msgError("删除失败: " + (error.message || "未知错误"))
        })
      })
    },
    
    // 导出操作
    handleExport() {
      this.download('collect/favorites/export', {
        ...this.queryParams
      }, `favorites_${new Date().getTime()}.xlsx`)
    }
  }
}
</script>

<style scoped>
.app-container {
  padding: 20px;
}

.dialog-footer {
  text-align: right;
}

.el-table {
  width: 100%;
}

/* 头像样式优化 */
.el-avatar {
  border: 1px solid #eee;
}
</style>
